package com.devops.admin.special;

import com.devops.admin.model.DOSExportDataJob;
import com.devops.admin.service.DOSExportDataJobService;
import com.devops.constant.JobGroupEnum;
import com.devops.admin.job.ExportDataJob;
import com.devops.admin.job.JobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.SchedulerException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jxt
 * @Notes 由于启动的job是存到memory的，故启动时要加载
 * @date 2024/1/10 11:12
 */
@Slf4j
@Component
public class ActiveJobApplicationRunner implements ApplicationRunner {
    @Resource
    private DOSExportDataJobService dosExportDataJobService;
    @Resource
    private JobService jobService;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        dosExportDataJobService.lambdaQuery()
                .eq(DOSExportDataJob::getActive, true)
                .list()
                .forEach(this::startJob);
    }

    private void startJob(DOSExportDataJob exportDataJob) {
        try {
            Map<String, Object> dataMap = new HashMap<>(8);
            dataMap.put("jobId", exportDataJob.getId());
            jobService.startCronJob(exportDataJob.getCronExpression(), ExportDataJob.class,
                    exportDataJob.getId().toString(), JobGroupEnum.EXPORT_DATA.toString(), new JobDataMap(dataMap));
        } catch (SchedulerException e) {
            log.info(e.getMessage());
        }
    }
}
